import 'package:dio/dio.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/token.dart';

class NetworkService {
  final Dio _dio = Dio();

  NetworkService() {
    //  设置请求头
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    // 设置超时时间
    _dio.options.connectTimeout = Duration(seconds: 5000);
    //  设置响应时间
    _dio.options.receiveTimeout = Duration(seconds: 5000);
    //添加拦截器
    _addInterceptors();
  }

  _addInterceptors() {
    //添加拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(
        //请求拦截器
        onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
          //添加一些自定义参数如 token。
          final token = TokenManager().getToken();
          if (token != null) {
            options.headers["Authorization"] = 'Bearer $token';
          }
          //继续处理请求
          return handler.next(options);
        },
        //响应拦截器
        onResponse: (Response response, ResponseInterceptorHandler handler) {
          // 打印响应的数据
          print(response.data);
          return handler.next(response);
        },
        //错误拦截
        onError: (DioException error, ErrorInterceptorHandler handler) {
          // 如果你想完成请求并返回一些自定义数据，你可以使用 `handler.resolve(response)`。
          return handler.next(error);
        },
      ),
    );
  }

  // get请求
  get(String url, {Map<String, dynamic>? queryParameters}) async {
    try {
      Response res = await _dio.get(url, queryParameters: queryParameters);
      return _handleResponse(res);
    } catch (error) {
      _handleError(error);
    }
  }

  //post请求
  post(String url, {Object? data}) async {
    try {
      Response res = await _dio.post(url, data: data);
      return _handleResponse(res);
    } catch (error) {
      _handleError(error);
    }
  }

  //put请求
  put(String url, {Object? data}) async {
    try {
      Response res = await _dio.put(url, data: data);
      return _handleResponse(res);
    } catch (error) {
      _handleError(error);
    }
  }

  //delete请求
  delete(String url, {Object? data}) async {
    try {
      Response res = await _dio.delete(url, data: data);
      return _handleResponse(res);
    } catch (error) {
      _handleError(error);
    }
  }

  _handleResponse(Response res) {
    if (res.statusCode! >= 200 && res.statusCode! <= 300) {
      return res.data;
    } else {
      throw Exception('请求失败，状态码：${res.statusCode}');
    }
  }

  dynamic _handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        if (error.response?.statusCode == 401) {
          //清空token
          TokenManager().removeToken();
          //跳转到登录页面
          eventBus.fire(LogoutEvent);
        } else {
          throw Exception('响应错误，状态码：${error.response?.statusCode}');
        }
      } else {
        throw Exception('网络请求出现了一个hhhhhhhhhhhhh错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }
}

//单例模式导出实例
final http = NetworkService();
